package com.it.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.it.filter.JwtAuthFilter;
import com.it.utils.JwtUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

@Configuration
@EnableWebSecurity
public class JwtSecurityConfig {

	@Autowired
	private AuthenticationProvider authenticationProvider;

	@Autowired
	private JwtAuthFilter jwtAuthFilter;

	@Autowired
    private JwtUtils jwtUtils;

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
				// 开启csrf才可以缓存请求
				.csrf(AbstractHttpConfigurer::disable)
				.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
				.formLogin(login -> login
						.successHandler((request, response, authentication) -> {
							ResponseEntity<String> result;
							if (authentication != null) {
								UserDetails user = (UserDetails) authentication.getPrincipal();
								String token = jwtUtils.generateToken(user);
								result = ResponseEntity.ok(token);
							} else {
								result = ResponseEntity.status(400).body("Some error has occurred");
							}
							response.getWriter().write(JSONUtil.toJsonStr(result));
                        })
				)
				.authorizeHttpRequests(authorize -> authorize
						.requestMatchers("/login").permitAll()
						.anyRequest().authenticated()
				)
				// .exceptionHandling(exc -> exc.authenticationEntryPoint((request, response, authException) -> {
				// 	String jsonStr = "{\"code\":20000,\"msg\":\"用户未登录\"}";
				// 	response.setStatus(200);
				// 	response.setContentType("application/json");
				// 	response.setCharacterEncoding("utf-8");
				// 	response.getWriter().print(jsonStr);
				// }))
				.authenticationProvider(authenticationProvider)
				.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
		return http.build();
	}

	@Bean
	public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
		return config.getAuthenticationManager();
	}

}
